package com.itdev.matcherapp.android;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentReceiver;
import android.content.ServiceConnection;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Binder;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.widget.Toast;

import com.google.android.gtalkservice.IGTalkService;
import com.google.android.gtalkservice.IGTalkSession;
import com.google.android.maps.Point;
import com.itdev.matcher.server.domain.User;
import com.itdev.matcherapp.android.fakeservice.PeopleLocationBean;
import com.itdev.matcherapp.android.fakeservice.ServiceEnterprise;
import com.itdev.matcherapp.android.fakeservice.ServiceFaky;

public class PeopleFillterService extends Service {
	private int count = 0;
	public static final String ACTION_LOCATION_CHANGE_PROCESSING = "com.itdev.matcj=herapp.android.ACTION_LOCATION_CHANGE_PROCESSING";
	private static final float MINIMUM_LOCATION_CHANGE_UPDATE = 1.0f;
	public static final String PROVIDER_NAME = "test1";
	private static final int MINIMUM_TIME_UPDATE = 100;
	public static boolean canUpdate = true;
	private IGTalkSession mGTalkSession;
	private float raduisFilter = 1.0f;
	private final IBinder mBinder = new LocalBinder();
	private Intent intentLocationChangeProcessing = new Intent(ACTION_LOCATION_CHANGE_PROCESSING);
	private IntentReceiver intentReceiver = new IntentReceiverBroadcastLocationChange();
	private IntentFilter intentFilter = new IntentFilter(ACTION_LOCATION_CHANGE_PROCESSING);
	private LocationManager locationManager;
	private LocationProvider locationProvider;
	static{
		ServiceFaky.initInstance();
	}
	
	public class LocalBinder extends Binder {
		PeopleFillterService getService() {
			return (PeopleFillterService) PeopleFillterService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	@Override
	protected void onCreate() {
		bindService((new Intent()).setComponent(
                com.google.android.gtalkservice.GTalkServiceConstants.GTALK_SERVICE_COMPONENT),
                mConnection, 0);
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		locationProvider = locationManager.getProvider(PROVIDER_NAME);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(mConnection);
		unregisterReceiver(intentReceiver);
		unbroadcastStickyIntent(intentLocationChangeProcessing);
		locationManager.removeUpdates(intentLocationChangeProcessing);
		this.stopSelf();
	}
	
	@Override
	protected void onStart(int startId, Bundle arguments) {
		if(count<=0){
			super.onStart(startId, arguments);
			locationManager.requestUpdates(locationProvider, MINIMUM_TIME_UPDATE, MINIMUM_LOCATION_CHANGE_UPDATE, intentLocationChangeProcessing);
			registerReceiver(intentReceiver, intentFilter);
			count++;
		}
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			IGTalkService GTalkService = IGTalkService.Stub
					.asInterface(service);

			try {
				mGTalkSession = GTalkService.getDefaultSession();

				if (mGTalkSession == null) {
					// this should not happen.
					return;
				}
			} catch (DeadObjectException ex) {
				// showMessage("Session not found");
			}

		}

		public void onServiceDisconnected(ComponentName className) {
			// This is called when the connection with the service has been
			// unexpectedly disconnected -- that is, its process crashed.
			mGTalkSession = null;
			// mSendButton.setEnabled(false);
		}
	};
	
	public IGTalkSession getGTalkSession(){
		return mGTalkSession;
	}
	
	public Location getCurrentLocation(){
		if(locationManager != null){
			return locationManager.getLastKnownLocation(PROVIDER_NAME);
		}
		return null;
	}

	public float getRaduisFilter() {
		return raduisFilter;
	}
	public static int notUpdate = 0;
}

class IntentReceiverBroadcastLocationChange extends IntentReceiver{
	
	@Override
	public void onReceiveIntent(Context context, Intent intent) {
		if(!Map.canUpdate) {
			PeopleFillterService.notUpdate++;
			return;
		}
		PeopleFillterService filterService = (PeopleFillterService) context;
		String myAccount = null;
		try {
			if(filterService.getGTalkSession()==null) {
				Toast.makeText(filterService, "NUll", Toast.LENGTH_SHORT).show();
				return;
			}else{
//				Toast.makeText(filterService, "NOT NUll", Toast.LENGTH_SHORT).show();
			}
			myAccount = filterService.getGTalkSession().getUsername();
		} catch (DeadObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Point curPoint = new Point((int)(filterService.getCurrentLocation().getLatitude()*1E6), 
				(int)(filterService.getCurrentLocation().getLongitude()*1E6));
		//============================================================
		//ServiceFaky.updateCurrentLocation(myAccount, curPoint);
		//============================================================
		//------------------------------------------------------------
		User user = new User();
		user.setUserMailAccount(myAccount);
		user.setUserLatE6(curPoint.getLatitudeE6());
		user.setUserLngE6(curPoint.getLongitudeE6());
		ServiceEnterprise.updateMyLocation(user);
		//------------------------------------------------------------
		Intent intentForMapToBroadcast = new Intent(Map.ACTION_LOCATION_CHANGE);
		Location loc = (Location) intent.getExtra("location");
		intentForMapToBroadcast.putExtra("location", loc);
		//===============================================================================
		//List<PeopleLocationBean> peopleList = 
		//	ServiceFaky.getPeopleMatching(myAccount, filterService.getRaduisFilter());
		//===============================================================================
		//-------------------------------------------------------------------------------
		List<User> peopleAround = ServiceEnterprise.getPeopleNearMe(user, 1.0f);
		List<PeopleLocationBean> peopleList = new ArrayList<PeopleLocationBean>();
		for(User person : peopleAround){
			PeopleLocationBean plb = new PeopleLocationBean();
			plb.setGmailAccount(person.getUserMailAccount());
			plb.setLatitude(person.getUserLatE6());
			plb.setLongitude(person.getUserLngE6());
			peopleList.add(plb);
		}
		
		//-------------------------------------------------------------------------------
		intentForMapToBroadcast.putExtra("peoplelist", (Serializable)peopleList);
		filterService.broadcastIntent(intentForMapToBroadcast);
	}
	
}
